package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.entity.AreaCity;
import com.caocaog.market.entity.AreaDistrict;
import com.caocaog.market.entity.AreaProvince;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.merchant.entity.MkMerchantBasic;
import com.caocaog.market.merchant.service.MkMerchantService;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.service.IShopChannelshopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 店铺信息表
 *
 * @author guofeiyan
 * @date 2021-11-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "shopBasic", tags = "店铺信息表")
@RequestMapping("/shop/shopBasic")
public class ShopBasicController extends JeecgController<ShopBasic, IShopBasicService> {
    @Autowired
    private IShopBasicService shopBasicService;
    @Autowired
    private IShopChannelshopService shopChannelshopService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private MkMerchantService mkMerchantService;


    /**
     * 分页列表查询
     *
     * @param shopBasic
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "店铺信息表-分页列表查询")
    @ApiOperation(value = "店铺信息表-分页列表查询", notes = "店铺信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShopBasic shopBasic,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<ShopBasic> queryWrapper = QueryGenerator.initQueryWrapper(shopBasic, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
            if (2 == loginUser.getUserType()) {

                //分站
                String siteId = loginUser.getSiteId();
                //获取商户ids
                List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                //获取门店
                if (oConvertUtils.listIsNotEmpty(merchantIds)) {
                    queryWrapper.in("merchant_id", merchantIds);
                    queryWrapper.orderByAsc("audit");
                } else {
                    return Result.error("当前分站先还没有门店哟~");
                }

            } else if (3 == loginUser.getUserType()) {
                //商户
                String merchantId = loginUser.getMerchantId();
                // 首先获取选择的门店
//                if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
//                    queryWrapper.in("id", loginUser.getCurrentSelectedShopId());
//                } else {
                //获取门店
                queryWrapper.eq("merchant_id", merchantId);
                queryWrapper.orderByAsc("audit");
                queryWrapper.eq("status", 0);
//                }

            }
        }

        Page<ShopBasic> page = new Page<ShopBasic>(pageNo, pageSize);
        IPage<ShopBasic> pageList = shopBasicService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 商家端-列表查询-分类
     *
     * @param shopBasic
     * @return
     */
    @AutoLog(value = "商家端-列表查询-分类")
    @ApiOperation(value = "商家端-列表查询-分类", notes = "params:id必传")
    @GetMapping(value = "/queryShopListForMerchant")
    public Result<?> queryShopListForMerchant(ShopBasic shopBasic) {
        if (oConvertUtils.isEmpty(shopBasic.getId())) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper<ShopBasic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopBasic::getId, shopBasic.getId());
        List<ShopBasic> shopBasicList = shopBasicService.list(queryWrapper);
        return Result.OK(shopBasicList);
    }

    /**
     * 列表查询
     *
     * @param shopBasic
     * @return
     */
    @AutoLog(value = "店铺信息表-列表查询(无分页)")
    @ApiOperation(value = "店铺信息表-列表查询(无分页)", notes = "店铺信息表-列表查询(无分页)")
    @GetMapping(value = "/listAll")
    public Result<?> queryList(ShopBasic shopBasic, HttpServletRequest req) {
        QueryWrapper<ShopBasic> queryWrapper = QueryGenerator.initQueryWrapper(shopBasic, req.getParameterMap());
        List<ShopBasic> shopBasicList = shopBasicService.list(queryWrapper);
        return Result.OK(shopBasicList);
    }


    /**
     * TODO 优化
     */
    @AutoLog(value = "下拉数据 门店列表 筛选")
    @ApiOperation(value = "下拉数据 门店列表 筛选", notes = "下拉数据 门店列表 筛选")
    @GetMapping(value = "/selectShopList")
    public Result<?> selectShopList() {
        //判断权限
        QueryWrapper<ShopBasic> queryWrapper = new QueryWrapper<ShopBasic>();

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
            if (2 == loginUser.getUserType()) {

                //分站
                String siteId = loginUser.getSiteId();
                //获取商户ids
                List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                //获取门店
                if (oConvertUtils.listIsNotEmpty(merchantIds)) {
                    queryWrapper.in("merchant_id", merchantIds);

                }

            } else if (3 == loginUser.getUserType()) {
                //商户
                String merchantId = loginUser.getMerchantId();
                log.info("当前商户id:"+merchantId);
                //获取门店
                if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
                    log.info("当前商户id:"+merchantId+",选中门店id:"+loginUser.getCurrentSelectedShopId());
                    queryWrapper.in("id", loginUser.getCurrentSelectedShopId());
                } else {
                    queryWrapper.eq("merchant_id", merchantId);
                }

            }
//            queryWrapper.eq("status",1);
        }
        queryWrapper.eq("del_flag", 0);
        queryWrapper.eq("audit", 1);
        queryWrapper.eq("status", 0);
        List<ShopBasic> shopBasicList = shopBasicService.list(queryWrapper);
        for (ShopBasic shopBasic : shopBasicList) {
            MkMerchantBasic m = mkMerchantService.getById(shopBasic.getMerchantId());
            if (oConvertUtils.isEmpty(m)) {
                shopBasic.setName("-----" + shopBasic.getName());
            } else {
                shopBasic.setName(m.getName() + "-----" + shopBasic.getName());
            }
        }
        return Result.OK(shopBasicList);
    }

    @AutoLog(value = "省市区县街道-省")
    @ApiOperation(value = "省市区县街道-省", notes = "省市区县街道-省")
    @GetMapping(value = "/selectAreaProvinceList")
    public Result<?> selectAreaProvinceList() {
        List<AreaProvince> provinceList = shopBasicService.selectAreaProvinceList();
        return Result.OK(provinceList);
    }

    @AutoLog(value = "省市区县街道-市")
    @ApiOperation(value = "省市区县街道-市", notes = "省市区县街道-市")
    @GetMapping(value = "/selectAreaCityList/{id}")
    public Result<?> selectAreaCityList(@PathVariable(value = "id") Integer id) {
        List<AreaCity> areaCityList = shopBasicService.selectAreaCityList(id);
        return Result.OK(areaCityList);
    }

    @AutoLog(value = "省市区县街道-区")
    @ApiOperation(value = "省市区县街道-区", notes = "省市区县街道-区")
    @GetMapping(value = "/selectAreaDistrictList/{id}")
    public Result<?> selectAreaDistrictList(@PathVariable(value = "id") Integer id) {
        List<AreaDistrict> districtList = shopBasicService.selectAreaDistrictList(id);
        return Result.OK(districtList);
    }

    private static final String SELECT_ONE_FOR_SERVE = "店铺信息表-查询账号下第一个店铺信息（服务信息需要用）";

    @AutoLog(value = SELECT_ONE_FOR_SERVE)
    @ApiOperation(value = SELECT_ONE_FOR_SERVE, notes = SELECT_ONE_FOR_SERVE)
    @GetMapping(value = "/selectOne")
    public Result<?> selectOneByUserForServe() {
        return Result.OK(shopBasicService.selectOneByUserForServe());
    }

    // add-begin Author:chechen Date:20211206 for：新增店铺 for 服务信息
    private static final String ADD_FOR_SERVE = "店铺信息表-新增店铺for服务信息";

    @AutoLog(value = ADD_FOR_SERVE)
    @ApiOperation(value = ADD_FOR_SERVE, notes = ADD_FOR_SERVE)
    @PostMapping(value = "/addForServe")
    @RequiresPermissions("serve:shop")
    public Result<?> addForServe(@RequestBody ShopBasic shopBasic) {
        return Result.OK("新增店铺信息for服务信息成功", this.shopBasicService.addForServe(shopBasic));
    }
    // add-end Author:chechen Date:20211206


    /**
     * 添加
     *
     * @param shopBasic
     * @return
     */
    @AutoLog(value = "店铺信息表-添加")
    @ApiOperation(value = "店铺信息表-添加", notes = "店铺信息表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopBasic shopBasic) {
        //所在地
/*
        AreaDistrict areaDistrict = shopBasicService.selectAreaDistrictOne(shopBasic.getArea());
        if (null != areaDistrict) {
            String location = areaDistrict.getPName() + areaDistrict.getSName() + areaDistrict.getName();
            shopBasic.setLocation(location);
        }*/
        // add-begin Author:chechen Date:20211207 for：新增店铺时，自动插入分站、商家信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MkMerchantBasic byUserId = mkMerchantService.findByUserId(loginUser.getId());
        if (MarketConstant.USER_TYPE_SITE.equals(loginUser.getUserType()))
            throw new JeecgBootException("分站用户无法添加店铺, username-> " + loginUser.getUsername());
        if (MarketConstant.USER_TYPE_MERCHANT.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(byUserId.getId()))
                throw new JeecgBootException("用户暂未绑定商家, username-> " + loginUser.getUsername());
            shopBasic.setMerchantId(byUserId.getId());
        }
        // add-end Author:chechen Date:20211207

        /*ShopBasic shopBasic = new ShopBasic();
        BeanUtils.copyProperties(shopVo, shopBasic);*/
        shopBasic.setIsRest(null == shopBasic.getIsRest() ? 0 : shopBasic.getIsRest());//默认营业
        shopBasic.setGrade(null == shopBasic.getGrade() ? "0" : shopBasic.getGrade());//默认评分0
        shopBasic.setLevel(null == shopBasic.getLevel() ? "5" : shopBasic.getLevel());//默认普通店铺
        //默认客服手机号 商家手机号
        shopBasic.setServicePhone(byUserId.getMobile());
        shopBasicService.save(shopBasic);
        //频道
        if (oConvertUtils.isNotEmpty(shopBasic.getChannelId())) {
            shopChannelshopService.add(shopBasic);
        }

         /*// 外卖信息
        ShopTakeout shopTakeout = new ShopTakeout();
        if (oConvertUtils.isEmpty(shopVo.getShopId())) {
            return Result.error("参数错误");
        }

        BeanUtils.copyProperties(shopVo, shopTakeout);
        shopTakeout.setChannelId(shopBasic.getChannelId());
        shopTakeoutService.save(shopTakeout);
        // his
        ShopTakeoutHis his = new ShopTakeoutHis();
        BeanUtils.copyProperties(shopTakeout, his);
        his.setTackoutId(shopTakeout.getId());
        his.setId(null);
        shopTakeoutHisService.save(his);*/
        return Result.OK("添加成功！", true);
    }

    /**
     * 营业状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "营业状态开关更新-通过id更新")
    @ApiOperation(value = "营业状态开关更新-通过id更新", notes = "营业状态开关更新-通过id更新")
    @GetMapping(value = "/restStatusChange/{id}")
    public Result<?> restStatusChange(@PathVariable("id") String id) {
        ShopBasic shopBasic = shopBasicService.getById(id);
        shopBasic.setIsRest(shopBasic.getIsRest()==0 ? 1 : 0);
        shopBasic.setIsHot(null);
        shopBasic.setRecommend(null);
        shopBasicService.updateById(shopBasic);
        return Result.OK("操作成功", shopBasic);
    }

    /**
     * 编辑
     *
     * @param shopBasic
     * @return
     */
    @AutoLog(value = "店铺信息表-编辑")
    @ApiOperation(value = "店铺信息表-编辑", notes = "店铺信息表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ShopBasic shopBasic) {
        //所在地
      /*  AreaDistrict areaDistrict = shopBasicService.selectAreaDistrictOne(shopBasic.getArea());
        if (null != areaDistrict) {
            String location = areaDistrict.getPName() + areaDistrict.getSName() + areaDistrict.getName();
            shopBasic.setLocation(location);
        }*/
//        ShopBasic shopBasic = shopBasicService.getById(shopVo.getId());

//            BeanUtils.copyProperties(shopVo, shopBasic);
        shopBasicService.updateById(shopBasic);
        //频道
        if (oConvertUtils.isNotEmpty(shopBasic.getChannelId())) {
            shopChannelshopService.update(shopBasic);
        }
        // 外卖信息
        // his
       /* ShopTakeout takeout = shopTakeoutService.getOne(new QueryWrapper<ShopTakeout>().eq("shop_id", shopBasic.getId()));
        if (oConvertUtils.isNotEmpty(takeout)){
            ShopTakeoutHis his = new ShopTakeoutHis();
            BeanUtils.copyProperties(takeout, his);
            his.setTackoutId(takeout.getId());
            his.setId(null);
            shopTakeoutHisService.save(his);
            BeanUtils.copyProperties(shopVo, takeout);
            shopTakeoutService.updateById(takeout);
        }
*/
        return Result.OK("编辑成功!", true);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店铺信息表-通过id删除")
    @ApiOperation(value = "店铺信息表-通过id删除", notes = "店铺信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        shopBasicService.removeById(id);
        return Result.OK("删除成功!", true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "店铺信息表-批量删除")
    @ApiOperation(value = "店铺信息表-批量删除", notes = "店铺信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shopBasicService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!", true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店铺信息表-通过id查询")
    @ApiOperation(value = "店铺信息表-通过id查询", notes = "店铺信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShopBasic shopBasic = shopBasicService.getById(id);
        if (shopBasic == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(shopBasic);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param shopBasic
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopBasic shopBasic) {
        return super.exportXls(request, shopBasic, ShopBasic.class, "店铺信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopBasic.class);
    }

}
